package com.lzq.ioc;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 容器实现
 * @author zhiqian
 * 思路：通过反射获取构造方法实例化对象，放到map集合中
 *      容器提供设置Bean的方法 和 获取Bean的方法
 */
public class IOCContainer {
    // beanId 和 bean 的映射关系
    public Map<String, Object> beans = new ConcurrentHashMap<>();

    /**
     * 获取bean
     * @param beanId beanId
     * @return bean 对象
     */
    public Object getBean(String beanId) {
        return this.beans.get(beanId);
    }

    /**
     * 设置bean
     * @param clazz bean 的类
     * @param beanId beanId
     * @param paramBeanIds 要创建bean的class的构造方法所需要的参数
     */
    public void setBean(Class<?> clazz, String beanId, String... paramBeanIds) {
        // 1.组装构造方法所需要的参数值
        Object[] paramValues = new Object[paramBeanIds.length];
        for (int i = 0; i < paramBeanIds.length; i++) {
            String paramBeanId = paramBeanIds[i];
            Object paramBean = this.getBean(paramBeanId);
            paramValues[i] = paramBean;
        }
        // 2.调用构造方法实例化bean
        Object bean = null;
        Constructor<?>[] constructors = clazz.getConstructors();
        for (Constructor<?> constructor : constructors) {
            try {
                bean = constructor.newInstance(paramValues);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        // 3.把bean放到容器
        if (bean != null) {
            this.beans.put(beanId, bean);
        }
    }
}
